<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="850px"
      draggable
      @close="closeDialog"
      destroy-on-close
      align-center
      class="maxhDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="100"
        v-if="!props.isReadonly"
        style="width: 98%"
      >
        <div>
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="单据号"
                prop="recordCode"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.recordCode"
                  placeholder="保存时自动生成"
                  disabled
                  clearable
                />
                <span v-else>{{ formData.recordCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="产品"
                prop="currentProductId"
                style="width: 100%"
              >
                <el-select
                  v-if="!props.isReadonly"
                  v-model="formData.currentProductId"
                  placeholder="请选择产品"
                  clearable
                  style="width: 100%"
                  @change="currentProductChange"
                >
                  <el-option
                    v-for="item in productList"
                    :key="`${item.id}`"
                    :label="`${item.productName}`"
                    :value="`${item.id}`"
                  />
                </el-select>

                <span v-else>{{ formData.currentProductName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="申请日期"
                prop="applyDate"
                style="width: 100%"
              >
                <el-date-picker
                  style="width: 100%"
                  v-if="!props.isReadonly"
                  v-model="formData.applyDate"
                  type="date"
                  placeholder="请选择申请日期"
                  format="YYYY/MM/DD"
                  value-format="YYYY-MM-DD"
                />
                <span v-else>{{
                  dayjs(formData.applyDate).format("YYYY-MM-DD")
                }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="申请原因"
                prop="applyReason"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.applyReason"
                  placeholder="请输入申请原因"
                  clearable
                />
                <span v-else>{{ formData.applyReason }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="领用部门"
                prop="receiveDepartmentId"
                style="width: 100%"
              >
                <SelectOriganizationDangerGrant
                  v-if="!props.isReadonly"
                  @change="(ids:string) => getSelectIds(ids)"
                  @change-data="(datas:any) => getSelectDatas(datas)"
                  :isCheckStrictly="true"
                  :isMultiple="false"
                  :disabled="true"
                  :data="dataObject"
                  :selectData="formData.receiveDepartmentId"
                />
                <span v-else>{{ formData.receiveDepartmentName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="领用人"
                prop="receivePersonId"
                style="width: 100%"
              >
                <el-select
                  style="width: 100%"
                  v-if="!props.isReadonly"
                  v-model="formData.receivePersonId"
                  placeholder="请选择领用人"
                  clearable
                  disabled
                  @change="(e:any) => changePerson(e)"
                >
                  <el-option
                    v-for="(item, index) in personList"
                    :label="item.label"
                    :value="item.value"
                    :key="index"
                  />
                </el-select>
                <span v-else>{{ formData.receivePersonName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remarks" style="width: 100%">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.remarks"
                  placeholder="请输入备注"
                  type="textarea"
                  show-word-limit
                  :maxlength="255"
                  :autosize="{ minRows: 2, maxRows: 3 }"
                />
                <span v-else>{{ formData.remarks }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <el-row />
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <h4 class="mb-[20px] mt-[20px]">器具列表</h4>
          <el-button
            type="success"
            plain
            @click="openPrompt"
            v-if="!props.isReadonly"
          >
            <i-ep-plus />
            新增</el-button
          >
        </div>

        <div class="formTable">
          <el-table
            :data="formData.applyDetails"
            style="width: 100%"
            :key="Math.random"
            max-height="240px"
            overflow-y="auto"
            border
          >
            <el-table-column
              label="器具类型"
              min-width="150"
              align="center"
              prop="assetTypeName"
            />
            <el-table-column label="数量" min-width="150">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'applyDetails.' + $index + '.applyAmount'"
                  label-width="0"
                  :rules="rules.applyAmount"
                >
                  <el-input
                    v-if="!props.isReadonly"
                    v-model="row.applyAmount"
                    clearable
                    placeholder="请输入数量"
                  />
                  <span v-else>{{ row.applyAmount }}</span>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              width="150"
              v-if="!props.isReadonly"
            >
              <template #default="scope">
                <el-button
                  type="danger"
                  link
                  @click.stop="handleDelete(scope.$index)"
                  ><i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>

      <div v-if="props.isReadonly">
        <el-descriptions
          title=""
          :column="2"
          size="large"
          border
          style="width: 99%; margin-bottom: 20px"
        >
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">单据号</div>
            </template>
            {{ formData.recordCode || "" }}
          </el-descriptions-item>
          <!-- <el-descriptions-item>
            <template #label>
              <div class="cell-item">位置</div>
            </template>
            {{ formData.usePlaceName || "" }}
          </el-descriptions-item> -->
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">产品</div>
            </template>
            {{ formData.currentProductName || "" }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">申请日期</div>
            </template>
            {{ dayjs(formData.applyDate).format("YYYY-MM-DD") || "" }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">申请原因</div>
            </template>
            {{ formData.applyReason || "" }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">领用部门</div>
            </template>
            {{ formData.receiveDepartmentName || "" }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">领用人</div>
            </template>
            {{ formData.receivePersonName || "" }}
          </el-descriptions-item>

          <!-- <el-descriptions-item>
            <template #label>
              <div class="cell-item">换型产品</div>
            </template>
            {{ formData.changeProductName || "" }}
          </el-descriptions-item> -->
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">器具类型（当前产品）</div>
            </template>
            <div v-if="formData.currentDetails.length">
              <el-tag
                type="info"
                class="mr-2 mb-[8px]"
                v-for="(item, index) in formData.currentDetails"
                :key="index"
                >{{ item.assetTypeName }}</el-tag
              >
            </div>
            <div v-else>无</div>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">器具类型（换型产品）</div>
            </template>
            <div v-if="formData.changeDetails.length">
              <el-tag
                type="info"
                class="ml-2 mb-[8px]"
                v-for="(item, index) in formData.changeDetails"
                :key="index"
                >{{ item.assetTypeName }}</el-tag
              >
            </div>
            <div v-else>无</div>
          </el-descriptions-item>

          <el-descriptions-item :span="2" v-if="formData.remarks">
            <template #label>
              <div class="cell-item">备注</div>
            </template>
            {{ formData.remarks || "" }}
          </el-descriptions-item>
        </el-descriptions>
        <div v-if="formData.applyDetails.length">
          <h3
            class="mb-[5px] mt-[-3px] c-[#333] text-[15px] font-600 lh-[28px]"
          >
            器具列表
          </h3>

          <el-table
            :data="formData.applyDetails"
            style="width: 70%"
            :key="Math.random"
            max-height="240px"
            overflow-y="auto"
            border
          >
            <el-table-column
              label="器具类型"
              min-width="150"
              prop="assetTypeName"
              align="center"
            />
            <el-table-column
              label="数量"
              min-width="150"
              prop="applyAmount"
              align="center"
            />
          </el-table>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 新增领用列表 -->
    <el-dialog
      :close-on-click-modal="false"
      v-model="showImport"
      title="器具类型选择"
      destroy-on-close
      :width="450"
      draggable
      align-center
      class="showImport"
    >
      <el-form>
        <el-form-item label="器具类型" :label-width="90">
          <el-tree-select
            ref="selectTreeRef"
            v-model="typeSelectedIds"
            :data="catalogList"
            multiple
            :render-after-expand="false"
            show-checkbox
            placeholder="请选择器具类型"
            check-strictly
            check-on-click-node
            node-key="id"
            :props="{
              label: 'assetTypeName',
              value: 'id',
              children: 'nodes',
            }"
            filterable
            :filter-node-method="filterNodeMethod"
            :default-expand-all="true"
            style="width: 310px"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelImport">取消</el-button>
          <el-button type="primary" @click="confirmImport"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useUserStore } from "@/store/modules/user";
import { validatePositiveInteger, deepClone } from "@/utils/commonHooks";
import dayjs from "dayjs";

defineOptions({
  name: "EAMMTUSEAPPLYEDIT",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const typeSelectedIds = ref();

// 目录树
const catalogList: any = ref([]);

// 获取内容树数据
const getCAtalogList = async () => {
  // 获取内容树
  await request({
    url: "eam/eamCommon/getAvailableTree",
    method: "POST",
    data: { assetKind: 2 },
  }).then((res) => {
    catalogList.value = res.data;
  });
};

const selectTreeRef = ref();

// 多选框筛选
const filterNodeMethod = (value: string, data: any) => {
  return data.assetTypeName.includes(value);
};

// 选择作业
const showImport = ref(false);
function openPrompt() {
  showImport.value = true;
}

// 取消选择
function cancelImport() {
  showImport.value = false;
}

// 确定选择
async function confirmImport() {
  const list = selectTreeRef.value.getCheckedNodes();
  let applyDetails: any = [];
  list.map((item: any) => {
    const obj = {
      applyAmount: "1",
      assetTypeName: item.assetTypeName,
      assetTypeId: item.id,
    };
    applyDetails.push(obj);
  });
  formData.applyDetails = [...formData.applyDetails, ...applyDetails];
  showImport.value = false;
  typeSelectedIds.value = null;
}

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      if (!props.isReadonly) {
        formRef.value && formRef.value?.clearValidate();
        formRef.value && getCAtalogList();
      }
    }, 50);
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData: any = reactive({
  id: "",
  version: "",
  recordCode: "",
  usePlaceId: "",
  usePlaceName: "",
  applyDate: "",
  applyReason: "",
  receiveDepartmentId: useUserStore().user.parameters?.departmentId,
  receiveDepartmentName: useUserStore().user.parameters?.departmentName,
  receivePersonId: useUserStore().user.userId,
  receivePersonName: useUserStore().user.userName,
  remarks: "",
  assetKind: "",
  currentProductId: "",
  currentProductName: "",
  changeProductId: "",
  changeProductName: "",
  applyDetails: [],
  currentDetails: [],
  changeDetails: [],
  applyType: 1,
});

/** rules规则 */
const rules: any = reactive({
  recordCode: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  usePlaceId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  applyDate: [{ required: true, message: "请选择申请日期", trigger: "blur" }],
  applyReason: [
    { required: true, message: "请输入申请原因", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  receiveDepartmentId: [
    { required: true, message: "请选择领用部门", trigger: "change" },
  ],
  receivePersonId: [
    { required: true, message: "请选择领用人", trigger: "change" },
  ],
  currentProductId: [
    { required: true, message: "请选择当前产品", trigger: "change" },
  ],
  changeProductId: [
    { required: true, message: "请选择换型产品", trigger: "change" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  applyAmount: [
    { required: true, message: "请填写检具数量", trigger: "blur" },
    {
      validator: validatePositiveInteger,
      trigger: "blur",
    },
  ],
});

const isValidated = ref(false);
/** 删除行 */
const handleDelete = (index: any) => {
  formData.applyDetails.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, {
        ...props.data,
        applyDetails: props.data.applyDetails || [],
        changeDetails: props.data.changeDetails || [],
        currentDetails: props.data.currentDetails || [],
      });
      changeDept(formData.receiveDepartmentId);
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  if (formRef.value && formRef.value?.resetFields) {
    formRef.value && formRef.value?.resetFields();
    formRef.value && formRef.value?.clearValidate();
  }
  formData.id = "";
  formData.version = "";
  formData.recordCode = "";
  formData.usePlaceId = "";
  formData.usePlaceName = "";
  formData.applyDate = "";
  formData.applyReason = "";
  formData.receiveDepartmentId = useUserStore().user.parameters?.departmentId;
  formData.receiveDepartmentName =
    useUserStore().user.parameters?.departmentName;
  formData.receivePersonId = useUserStore().user.userId;
  formData.receivePersonName = useUserStore().user.userName;
  formData.remarks = "";
  formData.assetKind = "";
  formData.currentProductId = "";
  formData.currentProductName = "";
  formData.changeProductId = "";
  formData.changeProductName = "";
  formData.applyDetails = [];
  formData.currentDetails = [];
  formData.changeDetails = [];
  formData.applyType = 1;
}

const loading = ref(false);

/** 发放记录保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/eam/eammtuseapply/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

/** 选择组织机构并赋值id  start **/
function getSelectIds(ids: [] | string) {
  console.log("getSelectIds", ids);

  formData.receivePersonId = "";
  formData.receivePersonName = "";
  formData.receiveDepartmentId = ids;
  personList.value = [];
  changeDept(ids);
}
/** 选择组织机构并赋值Name   start **/
function getSelectDatas(datas: any) {
  formData.receiveDepartmentName = datas.organizationName
    ? datas.organizationName
    : "";
}

const dataObject = {
  name: "领用部门",
  defaultProps: {
    children: "nodes",
    label: "organizationName",
    value: "id",
  },
  api: "/system/sysOrganization/getUsableTree",
};
// 点击组织机构 选择人员
const personList: any = ref([]);
const changeDept = async (id) => {
  if (id) {
    const res = await request({
      url: "/system/sysUser/getList ",
      method: "post",
      data: {
        departmentId: id,
      },
    });
    personList.value = res.data;
    personList.value.map((item: any) => {
      item.label = `${item.firstName}`;
      item.value = `${item.id}`;
    });
  }
};

// 人员改变时
const changePerson = (e: any) => {
  if (e) {
    personList.value.forEach((item: any) => {
      if (item.id == e) {
        formData.receivePersonName = item.firstName;
      }
    });
  } else {
    formData.receivePersonId = "";
    formData.receivePersonName = "";
  }
};

// 获取产品信息下拉树
const productList: any = ref([]);
const getProductList = async () => {
  const { data } = await request({
    url: "/mdm/mdmproductinfo/getList",
    method: "POST",
    data: {
      enabled: 1,
    },
  });
  productList.value = data;
};

// 当前产品选择
function currentProductChange(e) {
  if (e) {
    formData.currentProductName =
      productList.value.filter((item) => item.id === e)[0]?.productName || "";
    getApplyDetails();
  } else {
    formData.currentProductName = "";
    formData.currentProductId = "";
    formData.currentDetails = [];
    formData.applyDetails = [];
  }
}

// 获取领用列表
async function getApplyDetails() {
  const { data } = await request({
    url: "/eam/eamproductassetmodel/list/only",
    method: "POST",
    data: {
      productId: formData.currentProductId,
    },
  });
  let arr: any = [];
  data?.map((item: any) => {
    arr.push({
      ...item,
      applyAmount: "1",
    });
  });
  formData.applyDetails = arr || [];
}

onMounted(() => {
  getProductList();
  if (formData.receiveDepartmentId) {
    changeDept(formData.receiveDepartmentId);
  }
});
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}
.formTable {
  :deep(.el-form-item) {
    margin: 0 0 13px 0 !important;
    width: 100%;
  }
}

:deep(.el-dialog .formTable .el-table .el-form-item) {
  padding: 11px 0 0 0 !important;
}
:deep(.el-dialog .formTable .el-table .el-form-item__error) {
  font-size: 11px !important;
}

:deep(.el-dialog .formTable .el-table) {
  .el-table__body td.el-table__cell {
    padding: 0 !important;
  }
}

:deep(
    .el-dialog .search-container .el-form-item--default .el-form-item__label
  ) {
  // 固定宽度
  justify-content: end;
}

:deep(.maxhDialog .el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto;
  padding: 20px;
}
.el-form-item {
  margin-bottom: 15px;
}
:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 120px;
}
:deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
  min-width: 180px;
  word-break: break-all;
}
</style>
